package tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBTools {
    // 定义一个加载驱动的变量
    static String driver="com.mysql.jdbc.Driver";
    //连接数据库的变量
    static String url = "jdbc:mysql://localhost:3306/businformanagedb";
    static String user = "root";
    static String password = "1234";
    static Connection conn = null;
    //使用一个静态构造块完成驱动的加载
    static{
        try {
            Class.forName(driver);//加载驱动
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("驱动加载成功");
        }
    }
    //定义一个静态方法getConn:用来连接数据库
    public static Connection getConn(){
        try {
            conn=DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    //定义一个静态方法close：释放资源
    public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}